package com.geezdata.cps.sdk3rd.wyeth;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.geezdata.cps.base.enums.ErrorCode;
import com.geezdata.cps.base.response.BaseResponse;
import com.geezdata.cps.base.utils.HttpClientUtil;
import com.geezdata.cps.sdk3rd.wyeth.request.WyethRequest;
import com.geezdata.cps.sdk3rd.wyeth.response.WyethResult;

public class WyethDefaultClient implements WyethClient{
	private static final Logger logger = LoggerFactory.getLogger(WyethDefaultClient.class);
    
    private String serverUrl; 
    
    public WyethDefaultClient(String serverUrl) {
        this.serverUrl = serverUrl;
    }
    
    public <T extends WyethResult> BaseResponse<T> execute(WyethRequest<T> request) {
        // 1、惠氏通微信不需要接口认证
        // 2、Request及自身参数检查
    	if(request == null) {
    		return BaseResponse.error(ErrorCode.INVALID_PARAMS.getCode(), ErrorCode.INVALID_PARAMS.getDesc());
        }
        
        // 3、检查apiParams
        Map<String,Object> paramsMap =  request.getApiParams();
        if( paramsMap == null ||  paramsMap.isEmpty() ) {
        	return BaseResponse.error(ErrorCode.INVALID_PARAMS.getCode(), "empty request api params");
        }
        
      
        // 5、发送报文并获取响应的报文串
        String respJsonStr = null;
        try {
            respJsonStr = HttpClientUtil.get(serverUrl, paramsMap);
        } catch (Exception e) {
        	return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), e.getMessage());
        }
        
        // 6、将返回封装成对应的Response
        if(StringUtils.isEmpty(respJsonStr)){
            logger.warn("resp Json String is empty");
            return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), "resp Json String is empty");
        }
        
        
        T wyethResult = null;
        try {
        	wyethResult = request.getResponseClass().newInstance();
        	wyethResult.parseResponseJsonStringToResponse(respJsonStr);
        } catch (Exception e) {
            logger.error("", e);
            return BaseResponse.error(ErrorCode.HTTP_EXCEPTION.getCode(), e.getMessage());
        }

        return (BaseResponse<T>) BaseResponse.success(wyethResult);
    }

}
